package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.VmTypeMapper;
import com.heima.pojo.VmType;
import com.heima.pojo.dto.VmTypeDto;
import com.heima.pojo.dto.VmTypePageDto;
import com.heima.pojo.vo.VmTypePageVo;
import com.heima.pojo.vo.VmTypeVo;
import com.heima.service.VmTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor
public class VmTypeServiceImpl implements VmTypeService {

    @Autowired
    private VmTypeMapper vmTypeMapper;

    /**
     * 设备分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public VmTypePageVo pageQuery(VmTypePageDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        Page<VmType> vmTypes = vmTypeMapper.pageQuery(dto);
        VmTypePageVo vmTypePageVo = new VmTypePageVo();
        vmTypePageVo.setPageIndex(dto.getPageIndex());
        vmTypePageVo.setPageSize(dto.getPageSize());
        vmTypePageVo.setTotalCount(vmTypes.getTotal());
        vmTypePageVo.setTotalPage(vmTypes.getPages());
        vmTypePageVo.setCurrentPageRecords(vmTypes);
        return vmTypePageVo;
    }

    /**
     * 新增设备类型
     *
     * @param dto
     */
    @Override
    public void save(VmTypeDto dto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(dto, vmType);
        Optional<String> typeId = Optional.ofNullable(dto.getTypeId());
        if (typeId.isEmpty()) {
            // 新增
            vmTypeMapper.insert(vmType);
        }else {
            //修改
            vmTypeMapper.update(vmType);
        }
    }

    /**
     * 根据id删除设备
     * @param typeId
     */
    @Override
    public void delById(Integer typeId) {
        vmTypeMapper.delById(typeId);
    }
}
